<template>
  <div>
    <jm-head></jm-head>

    <input type="file" id="fileInput" accept="image/png,image/gif,image/jpeg" ref="fileInput" v-on:change="addImg"/>

    <section class="form">

        <section class="album_name">
          <input type="text" placeholder="相册名" v-model="title" @blur="titleRight">
        </section>

        <section class="room_cover">
          <section class="img_box" @click="uploadClick" :class="{'img_box_active': show }">
            <i class="icon_style iconfont icon-tupian1" slot="item_btn" v-show="!show && !showLoad"></i>
            <span v-show="!show && !showLoad">相册封面</span>
            <img src="" alt="" id="img_show" v-show="show" class="cover">
            <spinner type="snake" v-show="showLoad" class="load_icon"></spinner>
          </section>
        </section>

        <section class="album_desc">
          <textarea class="input_item" placeholder="请输入相册描述" v-model="desc" @blur="descRight"></textarea>
        </section>
    </section>

    <button class="btn" @click="create">创建相册</button>
    <jm-footer></jm-footer>
  </div>

</template>

<script>
  import JmHead from '../../components/header/Head';
  import JmFooter from '../../components/footer/Footer';
  import CryptoJS from 'crypto-js'
  import Uploader from '../../service/nos-js-sdk';
  import {mapState, mapMutations} from 'vuex'
  import { Toast,Spinner } from 'mint-ui';

  export default {
    data () {
      return {
        title: null,  //相册标题
        desc: null,  //相册描述
        coverUrl:null,  //相册封面的url
        result: null,  //创建空间的结果
        show: false,  //展示图片
        showLoad: false, //展示加载
      }
    },

    methods: {
      titleRight(){
        if (this.title === null){
          let instance = Toast({message: '相册名不能为空', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
          return
        }

        if (this.title.length > 10){
          let instance = Toast({message: '相册名长度不能超过10位', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
          return
        }

      },
      descRight(){
        if (this.desc === null){
          let instance = Toast({message: '相册描述不能为空', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
          return
        }
      },
      uploadClick(){
        document.getElementById("fileInput").click();
      },

      addImg(){
        let fileinput = document.getElementById('fileInput');
        let image = fileinput.files[0];

        let reader = new FileReader();
        reader.readAsBinaryString(image);

        reader.onload = function (e) {
          let name = CryptoJS.MD5(e.target.result)+'.jpg';
          this.uploadImg(image, name);
        }.bind(this)

      },

      showImg(fileName){
        this.show = true;
        this.showLoad = false;
        this.coverUrl = fileName;
        document.getElementById("img_show").src =this.$store.state.baseImgUrl +  this.coverUrl;
      },


      uploadImg(image, fileName){
        this.showLoad = true;
        let that = new Uploader();

        let param = {
          bucketName: 'jimikongjian',
          objectName: fileName,
          token: this.getToken(fileName),
          trunkSize: 4 * 1024 * 1024,
        }

        if (image) {
          that.addFile(image, function(curFile){
            console.log(curFile.fileName + ' is added.');
          });
          that.upload(param, function(curFile){
            console.log('File: ' + curFile.fileName + ' is uploaded.');
            this.showImg(fileName);
          }.bind(this));

        }

      },


      //获取上传凭证
      getToken(Object){
        let p = {
          "Bucket" : "jimikongjian",
          "Object" : Object,
          "Expires" : this.$store.state.expiresTime
        }
        let putPolicy = JSON.stringify(p);
        let wordArray = CryptoJS.enc.Utf8.parse(putPolicy);
        let encodedPutPolicy = CryptoJS.enc.Base64.stringify(wordArray);
        let sign = CryptoJS.HmacSHA256(encodedPutPolicy, this.$store.state.accessSecret);
        let encodedSign = CryptoJS.enc.Base64.stringify(sign);
        return "UPLOAD " + this.$store.state.accessKey + ":" + encodedSign + ":" + encodedPutPolicy;
      },



      async create(){
        if (this.title === null){
          let instance = Toast({message: '相册名不能为空', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
          return
        }
        if (this.coverUrl === null){
          let instance = Toast({message: '相册封面不能为空', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
          return
        }
        if (this.desc === null){
          let instance = Toast({message: '相册描述不能为空', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
          return
        }

        if (this.title.length > 10){
          let instance = Toast({message: '相册名长度不能超过10位', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
          return
        }
        let album = {
          userId: this.$store.state.userInfo.userId,
          userNick: this.$store.state.userInfo.nick,
          roomId: this.$store.state.roomDetail.id,
          roomName: this.$store.state.roomDetail.name,
          albumTitle: this.title,
          albumDesc: this.desc,
          photosCount: 1,
          cover1: this.coverUrl,
          cover2: "",
          cover3: "",
        }

        await this.axios.post('/v1/album', album)
          .then(response => {
            this.result = response.data;
          });
        if (this.result.success){
          let instance = Toast({message: '创建空间成功', className: 'toast'});
          setTimeout(() => {
            instance.close();
            this.$router.go(-1);
          }, 2000);

        }else{
          let instance = Toast({message: '网络连接失败', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
        }
      }


    },
    mounted () {

    },
    components:{
      Spinner,
      JmHead,
      JmFooter
    }
  }
</script>

<style lang="scss">
  .mint-toast-text{
    font-size: 0.6rem;
  }
  .toast{
    min-width: 180px;
    width: 180px;
    span{
      color: #FFFFFF;
    }
  }
  .mint-spinner-snake{
    margin: auto auto;
  }
</style>

<style lang="scss" scoped>
  @import '../../style/mixin';
  .load_icon{
    display: inline-block;
    height: 100%;
    width: 100%;
    position: relative;
    margin: 0 auto;
  }

  #fileInput{
    position: absolute;
    top: 0;
    left: 0;
    width: 0;
    height: 0;
  }


  .form{
    overflow: hidden;
    height: 332px;
    width: 80%;
    margin: 0 10%;
    margin-top: 2rem;
    margin-bottom: 0.7rem;
    border: solid 1px #666;
    @include borderRadius(15px);

    .album_name{
      height: 30px;
      width: 100%;
      border-bottom: solid 1px #666;

    }

    .room_cover{
      height: 150px;
      width: 100%;
      border-bottom: solid 1px #666;
      display: flex;

      .img_box{
        border: dashed 1px #666;
        width: 90%;
        height: 130px;
        margin: 10px auto;
        display: flex;
        text-align: center;
        flex-direction: column;
        align-items: center;

        .icon_style{
          color: #666;
          font-size: 69px;
          margin: auto auto;
        }
        span{
          font-size: 15px;
        }


        .cover{
          width: 100%;
          height: 100%;
          margin: 0;
        }

      }

    }

    .album_desc{
      height: 150px;
      width: 100%;
      /*border-bottom: solid 1px #666;*/
      @include borderRadius(15px);

      .input_item{
        height: 100%;
        width: 100%;
        font-size: 15px;
        text-indent: 13px;
        resize: none;
        @include borderRadius(15px);
      }
    }

    input{
      background-color: transparent;
      height: 100%;
      width: 100%;
      font-size: 15px;
      text-indent: 13px;
    }


    ::-webkit-input-placeholder{
      color: #666;
      font-size: 15px;
      text-indent: 13px;
    }
    :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
      color: #666;
      font-size: 15px;
      text-indent: 13px;
    }
    ::-moz-placeholder { /* Mozilla Firefox 19+ */
      color: #666;
      font-size: 15px;
      text-indent: 13px;
    }
    :-ms-input-placeholder { /* Internet Explorer 10+ */
      color: #666;
      font-size: 15px;
      text-indent: 13px;
    }

  }

  .btn{
    height: 30px;
    width: 80%;
    margin: 0 10%;
    background-color: #33CCFF;
    color: #FFFFFF;
    @include borderRadius(15px);
    font-size: 20px;
    font-weight: bold;
  }
</style>
